class UsersController < ApplicationController
  before_action :set_user, only: [:edit, :update, :destroy, :set_as_admin, :set_as_normal]
  def index
    @users = User.includes(:group).where.not(id: current_user.id)
  end

  def create
    @user = User.new(user_params)
    if @user.save
      log_in @user
      redirect_to root_path
    else
      redirect_to action: :new
    end
  end

  def edit
  end

  def new
    @user = User.new
    render layout: false
  end

  def show
    @user = User.find(params[:id])
    render "index"
  end

  def update
    @user.group_id = params[:user][:name].to_s
    @user.group_id = params[:user][:email].to_s
    @user.group_id = params[:user][:group_id].to_i
    @user.save
    redirect_to '/'
  end

  def set_as_admin
    @user.admin = true
    @user.save
    reload_users
  end

  def set_as_normal
    @user.admin = false
    @user.save
    reload_users
  end

  def destroy
    @user.destroy
    reload_users
  end

  private

    def reload_users
      redirect_to action: :index
    end

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end

    def set_user
      @user = User.find(params[:id])
    end
end
